import api from './api';
import { SignInTask, SignInRecord, Student } from '@/types';

// 接口返回类型
interface ApiResponse<T = any> {
  code: number;
  message: string;
  data?: T;
}

interface SignInTaskListResponse {
  tasks: SignInTask[];
}

interface SignInRecordListResponse {
  records: SignInRecord[];
}

// 签到学生详情类型
export interface SignInStudentDetail extends Student {
  signStatus: 'signed' | 'absent';
  signInTime?: string;
  signInMethod?: 'face' | 'manual' | null;
}

// 签到学生详情响应
export interface SignInStudentDetailResponse {
  students: SignInStudentDetail[];
  totalCount: number;
  signedCount: number;
  absentCount: number;
  signInRate: number;
}

// 签到统计结果类型
export interface ClassStatItem {
  classId: number;
  className: string;
  total: number;
  signedIn: number;
  absent: number;
  signInRate: number;
}

export interface StatisticsResult {
  totalTasks: number;
  totalStudents: number;
  signedIn: number;
  absent: number;
  signInRate: number;
  classStats: ClassStatItem[];
}

/**
 * 获取教师的签到任务列表
 * @param courseId 课程ID
 */
export const getSignInTasks = async (courseId: number): Promise<ApiResponse<SignInTaskListResponse>> => {
  try {
    console.log('获取签到任务列表，课程ID:', courseId);
    // 确保使用正确的URL格式
    const url = `/teacher/sign_in/tasks?course_id=${courseId}`;
    console.log('发送请求到URL:', url);
    
    const response = await api.get(url);
    console.log('获取签到任务响应:', response);
    return response;
  } catch (error) {
    console.error('获取签到任务失败:', error);
    throw error;
  }
};

/**
 * 创建签到任务
 * @param courseId 课程ID
 * @param classIds 班级ID列表
 * @param startTime 开始时间
 * @param endTime 结束时间
 * @param description 描述
 */
export const createSignInTask = async (
  courseId: number,
  classIds: number[],
  startTime: string,
  endTime: string,
  description: string
): Promise<ApiResponse> => {
  try {
    console.log('创建签到任务:', { courseId, classIds, startTime, endTime, description });
    const response = await api.post('/teacher/sign_in/create', { 
      course_id: courseId,
      class_ids: classIds,
      start_time: startTime,
      end_time: endTime,
      description
    });
    console.log('创建签到任务响应:', response);
    return response;
  } catch (error) {
    console.error('创建签到任务失败:', error);
    throw error;
  }
};

/**
 * 结束签到任务
 * @param taskId 签到任务ID
 */
export const endSignInTask = async (taskId: number): Promise<ApiResponse> => {
  try {
    console.log('结束签到任务:', taskId);
    const response = await api.post('/teacher/sign_in/end', { 
      task_id: taskId 
    });
    console.log('结束签到任务响应:', response);
    return response;
  } catch (error) {
    console.error('结束签到任务失败:', error);
    throw error;
  }
};

/**
 * 获取签到任务记录
 * @param taskId 签到任务ID
 */
export const getSignInRecords = async (taskId: number): Promise<ApiResponse<SignInRecordListResponse>> => {
  try {
    console.log('获取签到记录:', taskId);
    const response = await api.get(`/teacher/sign_in/records?sign_in_task_id=${taskId}`);
    console.log('获取签到记录响应:', response);
    return response;
  } catch (error) {
    console.error('获取签到记录失败:', error);
    throw error;
  }
};

/**
 * 手动为学生签到
 * @param taskId 签到任务ID
 * @param studentId 学生学号
 */
export const manualSignIn = async (taskId: number, studentId: string): Promise<ApiResponse> => {
  try {
    console.log('手动签到:', { taskId, studentId });
    const response = await api.post('/teacher/sign_in/manual', {
      sign_in_task_id: taskId,
      student_id: studentId
    });
    return response;
  } catch (error) {
    console.error('手动签到失败:', error);
    throw error;
  }
};

/**
 * 获取签到统计数据
 * @param params 查询参数
 * @param params.courseId 课程ID (可选)
 * @param params.classId 班级ID (可选)
 * @param params.startDate 开始日期 (格式: YYYY-MM-DD) (可选)
 * @param params.endDate 结束日期 (格式: YYYY-MM-DD) (可选)
 */
export const getSignInStatistics = async (params: {
  courseId?: number | string;
  classId?: number | string;
  startDate?: string;
  endDate?: string;
}): Promise<ApiResponse<StatisticsResult>> => {
  try {
    const queryParams: Record<string, any> = {};
    
    if (params.courseId) {
      queryParams.course_id = params.courseId;
    }
    
    if (params.classId) {
      queryParams.class_id = params.classId;
    }
    
    if (params.startDate) {
      queryParams.start_date = params.startDate;
    }
    
    if (params.endDate) {
      queryParams.end_date = params.endDate;
    }
    
    console.log('获取签到统计:', queryParams);
    const response = await api.get('/teacher/sign_in/statistics', { params: queryParams });
    console.log('获取签到统计响应:', response);
    return response;
  } catch (error) {
    console.error('获取签到统计失败:', error);
    throw error;
  }
};

/**
 * 获取签到任务详情
 * @param taskId 签到任务ID
 */
export const getSignInTaskDetail = async (taskId: number): Promise<ApiResponse<{ task: SignInTask }>> => {
  try {
    console.log('获取签到任务详情:', taskId);
    const response = await api.get(`/teacher/sign_in/detail?task_id=${taskId}`);
    console.log('获取签到任务详情响应:', response);
    return response;
  } catch (error) {
    console.error('获取签到任务详情失败:', error);
    throw error;
  }
};

/**
 * 获取签到任务学生列表
 * @param taskId 签到任务ID
 */
export const getSignInTaskStudents = async (taskId: number): Promise<ApiResponse<{ students: any[] }>> => {
  try {
    console.log('获取签到任务学生列表:', taskId);
    const response = await api.get(`/teacher/sign_in/students?task_id=${taskId}`);
    console.log('原始API响应:', response);
    
    // 确保我们有有效的学生数组，即使为空
    if (response.code === 0 || response.code === 2000) {
      if (!response.data) response.data = { students: [] };
      if (!response.data.students) response.data.students = [];
      
      // 确保是数组类型
      if (!Array.isArray(response.data.students)) {
        console.error('后端返回的students不是数组，尝试转换:', response.data.students);
        response.data.students = [];
      }
    }
    
    return response;
  } catch (error) {
    console.error('获取签到任务学生列表失败:', error);
    throw error;
  }
};

/**
 * 获取签到任务的详细学生签到状态
 * @param taskId 签到任务ID
 */
export const getSignInTaskStudentDetails = async (taskId: number): Promise<ApiResponse<SignInStudentDetailResponse>> => {
  try {
    console.log('开始获取签到任务详细学生状态, taskId:', taskId);
    
    // 1. 获取签到任务详情
    console.log('1. 调用getSignInTaskDetail API...');
    const taskRes = await getSignInTaskDetail(taskId);
    console.log('1. 签到任务详情响应:', JSON.stringify(taskRes));
    
    if (taskRes.code !== 0 && taskRes.code !== 2000) {
      console.error('获取签到任务详情失败:', taskRes.message);
      throw new Error(taskRes.message || '获取签到任务详情失败');
    }
    
    const courseId = taskRes.data?.task?.course_id;
    console.log('从任务详情中获取到courseId:', courseId);
    
    if (!courseId) {
      console.error('无法获取课程ID, taskRes.data:', taskRes.data);
      throw new Error('无法获取课程ID');
    }
    
    // 2. 获取课程学生列表
    console.log('2. 调用课程学生列表API, courseId:', courseId);
    const studentsRes = await api.get(`/teacher/course_student/list?course_id=${courseId}`);
    console.log('2. 课程学生列表原始响应:', studentsRes);
    console.log('2. 课程学生列表响应数据:', JSON.stringify(studentsRes));
    
    if (studentsRes.code !== 0 && studentsRes.code !== 2000) {
      console.error('获取课程学生列表失败:', studentsRes.message);
      throw new Error(studentsRes.message || '获取课程学生列表失败');
    }
    
    const students = studentsRes.data?.students || [];
    console.log('2. 获取到的学生数量:', students.length);
    if (students.length > 0) {
      console.log('2. 第一个学生数据示例:', JSON.stringify(students[0]));
    }
    
    // 3. 获取签到记录
    console.log('3. 调用getSignInRecords API...');
    const recordsRes = await getSignInRecords(taskId);
    console.log('3. 签到记录响应:', JSON.stringify(recordsRes));
    
    if (recordsRes.code !== 0 && recordsRes.code !== 2000) {
      console.error('获取签到记录失败:', recordsRes.message);
      throw new Error(recordsRes.message || '获取签到记录失败');
    }
    
    const records = recordsRes.data?.records || [];
    console.log('3. 获取到的签到记录数量:', records.length);
    if (records.length > 0) {
      console.log('3. 第一条签到记录示例:', JSON.stringify(records[0]));
    }
    
    // 4. 合并数据，生成详细的签到状态
    console.log('4. 开始合并数据...');
    const detailedStudents: SignInStudentDetail[] = students.map(student => {
      const record = records.find(r => r.student_id === student.student_id);
      console.log(`学生 ${student.name}(${student.student_id}) 签到状态:`, record ? '已签到' : '未签到');
      return {
        ...student,
        signStatus: record ? 'signed' : 'absent',
        signInTime: record?.sign_in_time,
        signInMethod: record?.sign_in_method
      };
    });
    
    // 5. 计算统计数据
    const totalCount = detailedStudents.length;
    const signedCount = detailedStudents.filter(s => s.signStatus === 'signed').length;
    const absentCount = totalCount - signedCount;
    const signInRate = totalCount > 0 ? Math.round((signedCount / totalCount) * 100) : 0;
    
    console.log('5. 统计数据:', {
      totalCount,
      signedCount,
      absentCount,
      signInRate
    });
    
    const result = {
      code: 2000,
      message: '获取签到任务详细学生状态成功',
      data: {
        students: detailedStudents,
        totalCount,
        signedCount,
        absentCount,
        signInRate
      }
    };
    
    console.log('6. 返回最终结果, 学生数量:', detailedStudents.length);
    return result;
  } catch (error) {
    console.error('获取签到任务详细学生状态失败:', error);
    throw error;
  }
}; 